import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:flutter_bxsh/config/http_headers.dart';
import '../service/service_method.dart';
import 'dart:convert';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:url_launcher/url_launcher.dart';
import 'dart:io';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {

  String homePageContent = '正在获取数据';

  int page = 1;
  List hotGoodsList = [];

  @override
  void initState() {
    _getHotGoodsData();
    super.initState();

  }

  @override
  Widget build(BuildContext context) {
    print("build");
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)
      ..init(context);
    var formData = {'lon': '115.02932', 'lat': '35.76189'};
    return Scaffold(
      appBar: AppBar(
        title: Text('百姓生活+'),
      ),
      body: SingleChildScrollView(
        child: Container(
          child: FutureBuilder(
              future: request("homePageContext", formData: formData),
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  var data = json.decode(snapshot.data.toString());
                  List<Map> swiper = (data['data']['slides'] as List).cast();
                  List<Map> navgatorList =
                  (data['data']['category'] as List).cast();
                  String adPicture =
                  data['data']['advertesPicture']['PICTURE_ADDRESS'];
                  //return SwiperDiy(swiperdDateList: swiper);
                  String leaderPhone =
                  data['data']['shopInfo']['leaderPhone'].toString();
                  String leaderImage =
                  data['data']['shopInfo']['leaderImage'].toString();

                  List<Map> recommendList =
                  (data['data']['recommend'] as List).cast();

                  String floor1Titile = data['data']['floor1Pic']['PICTURE_ADDRESS'];
                  String floor2Titile = data['data']['floor2Pic']['PICTURE_ADDRESS'];
                  String floor3Titile = data['data']['floor3Pic']['PICTURE_ADDRESS'];


                  List<Map> floor1 =
                  (data['data']['floor1'] as List).cast();
                  List<Map> floor2 =
                  (data['data']['floor2'] as List).cast();
                  List<Map> floor3 =
                  (data['data']['floor3'] as List).cast();

                  return SingleChildScrollView(
                    child: Column(
                      children: <Widget>[
                        SwiperDiy(swiperdDateList: swiper),
                        TopNavigator(navigetorList: navgatorList),
                        AdBanner(
                          adPicture: adPicture,
                        ),
                        LeaderPhone(
                          leaderImage: leaderImage,
                          leaderPhone: leaderPhone,
                        ),
                        Recommend(recommendList: recommendList),
                        FloorTitle(picture_address: floor1Titile,),
                        FloorContent(floorGoodsList: floor1,),
                        FloorTitle(picture_address: floor2Titile,),
                        FloorContent(floorGoodsList: floor2,),
                        FloorTitle(picture_address: floor3Titile,),
                        FloorContent(floorGoodsList: floor3,),
                        //HotGoods(),
                        _hotGoods(),
                      ],
                    ),
                  );
                } else {
                  return Center(
                    child: Text('加载中......'),
                  );
                }
              }),
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive {
    return true;
  }

  void _getHotGoodsData() {
    var fomdata = {"page": page};
    request("homePageBelowContent", formData: fomdata).then((value) {
      var data = json.decode(value.toString());
      List<Map> newGoodsList = (data['data'] as List).cast();
      setState(() {
        hotGoodsList.addAll(newGoodsList);
        page++;
      });
    });
  }

  Widget hotTile=Container(
    margin: EdgeInsets.only(top: 10.0,bottom: 5.0),
    alignment: Alignment.center,
    color: Colors.transparent,
    child:Text('火爆专区'),
  );

  
  Widget _listWrap(){
    if(hotGoodsList.length !=0){
      List<Widget>listWidget = hotGoodsList.map((value){
        return InkWell(
          onTap: (){
            
          },
          child: Container(
            width: ScreenUtil().setWidth(372),
            color: Colors.white,
            padding: EdgeInsets.all(5.0),
            margin: EdgeInsets.only(bottom: 3.0),
            child: Column(
              children: <Widget>[
                Image.network(value['image']),
                Text(value['name'],maxLines: 1,overflow: TextOverflow.ellipsis,style: TextStyle(
                  color: Colors.pink,fontSize: ScreenUtil().setSp(26)
                ),),
                Row(

                  children: <Widget>[
                    Text('¥${value['mallPrice']}'),
                    Expanded(

                      child:  Text('¥${value['price']}',textAlign: TextAlign.right,
                      style: TextStyle(color: Colors.black26,decoration: TextDecoration.lineThrough),
                    ),)

                  ],
                )
              ],
            ),
          ),
        );
      }).toList();
      return Wrap(
        spacing: 2,
        children: listWidget,
      );
    }else{
      return Text('');
    }
  }


  Widget _hotGoods(){
    return Container(
      child: Column(
          children: <Widget>[
            hotTile,
            _listWrap(),
          ],
      ),
    );
  }
  
}

//banner组件
class SwiperDiy extends StatelessWidget {
  final List swiperdDateList;

  SwiperDiy({Key key, this.swiperdDateList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    print('设备像素密度：${ScreenUtil.pixelRatio}');
    print('设备高度:${ScreenUtil.screenHeight}');
    print('设备的宽:${ScreenUtil.screenWidth}');

    return Container(
      height: ScreenUtil.instance.setHeight(333),
      width: ScreenUtil.instance.setWidth(750),
      color: Colors.green,
      child: Swiper(
        itemCount: swiperdDateList.length,
        itemBuilder: (BuildContext context, int index) {
          return Image.network(
            swiperdDateList[index]['image'],
            fit: BoxFit.fill,
          );
        },
        pagination: SwiperPagination(),
        loop: swiperdDateList.length > 1 ? true : false,
      ),
    );
  }
}

class TopNavigator extends StatelessWidget {
  final List navigetorList;

  TopNavigator({Key key, this.navigetorList}) : super(key: key);

  Widget _getItem(BuildContext context, item) {
    return InkWell(
      onTap: () {
        print('点击了导航');
      },
      child: Column(
        children: <Widget>[
          Image.network(
            item['image'],
            width: ScreenUtil().setWidth(95),
          ),
          Text(item['mallCategoryName']),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    if (navigetorList.length > 10) {
      navigetorList.removeRange(10, navigetorList.length);
    }
    return Container(
        height: ScreenUtil().setHeight(320),
        padding: EdgeInsets.all(3.0),
        child: GridView.count(
          crossAxisCount: 5,
          physics: NeverScrollableScrollPhysics(),
          padding: EdgeInsets.all(5.0),
          children: navigetorList.map((item) {
            return _getItem(context, item);
          }).toList(),
        ));
  }
}

//广告区域
class AdBanner extends StatelessWidget {
  final String adPicture;

  AdBanner({Key key, this.adPicture}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Image.network(adPicture),
    );
  }
}

//店长电话模块
class LeaderPhone extends StatelessWidget {
  final String leaderImage;
  final String leaderPhone;

  LeaderPhone({Key key, this.leaderImage, this.leaderPhone}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: InkWell(
        onTap: _telPhone,
        child: Image.network(leaderImage),
      ),
    );
  }

  void _telPhone() async {
    String url = 'tel:' + leaderPhone;
    if (await canLaunch(url))
      await launch(url);
    else
      throw '不能进行访问';
  }
}

//商品推荐类
class Recommend extends StatelessWidget {
  final List recommendList;

  Recommend({Key key, this.recommendList}) : super(key: key);

  //标题
  Widget _getTitleWiget() {
    return Container(
      padding: EdgeInsets.fromLTRB(10.0, 2.0, 0, 5.0),
      alignment: Alignment.centerLeft,
      decoration: BoxDecoration(
          color: Colors.white,
          border:
          Border(bottom: BorderSide(width: 0.5, color: Colors.black12))),
      child: Text(
        '商品推荐',
        style: TextStyle(color: Colors.pink),
      ),
    );
  }

  Widget _getProductItem(index) {
    return InkWell(
      onTap: () {},
      child: Container(
        //height: ScreenUtil().setHeight(340),
        width: ScreenUtil().setWidth(250),
        padding: EdgeInsets.all(8.0),
        decoration: BoxDecoration(
            color: Colors.white,
            border:
            Border(left: BorderSide(width: 0.5, color: Colors.black12))),
        child: Column(
          children: <Widget>[
            Image.network(recommendList[index]['image']),
            Text('¥${this.recommendList[index]['mallPrice']}'),
            Text(
              '¥${this.recommendList[index]['price']}',
              style: TextStyle(
                  color: Colors.grey, decoration: TextDecoration.lineThrough),
            )
          ],
        ),
      ),
    );
  }

  Widget _recList() {
    return Container(
      height: ScreenUtil().setHeight(340),
      child: ListView.builder(
          scrollDirection: Axis.horizontal,
          itemCount: recommendList.length,
          itemBuilder: (BuildContext context, index) {
            return _getProductItem(index);
          }),
    );
  }

  @override
  Widget build(BuildContext context) {
    recommendList.add(recommendList[0]);
    return Container(
      // height: ScreenUtil().setHeight(380),
      margin: EdgeInsets.only(top: 10),
      child: Column(
        children: <Widget>[_getTitleWiget(), _recList()],
      ),
    );
  }
}

//楼层标题
class FloorTitle extends StatelessWidget {
  final String picture_address;

  FloorTitle({Key key, this.picture_address}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(8.0),
      child: Image.network(picture_address),
    );
  }
}

//楼层商品列表
class FloorContent extends StatelessWidget {
  final List floorGoodsList;

  FloorContent({Key key, this.floorGoodsList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[_firstRow(), _otherGoods()],
      ),
    );
  }

  Widget _firstRow() {
    return Row(
      children: <Widget>[
        _goodsItem(floorGoodsList[0]),
        Column(
          children: <Widget>[
            _goodsItem(floorGoodsList[1]),
            _goodsItem(floorGoodsList[2]),
          ],
        )
      ],
    );
  }

  Widget _otherGoods() {
    return Row(
      children: <Widget>[
        _goodsItem(floorGoodsList[3]),
        _goodsItem(floorGoodsList[4])
      ],
    );
  }

  Widget _goodsItem(Map goods) {
    return Container(
      width: ScreenUtil().setWidth(375),
      child: InkWell(
        onTap: () {
          print("点击商品");
        },
        child: Image.network(goods['image']),
      ),
    );
  }
}



